package com.xiaolin.sports.controller;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaolin.sports.common.Configuration;
import com.xiaolin.sports.common.Constants;
import com.xiaolin.sports.common.RspResult;
import com.xiaolin.sports.common.enums.OrderStatus;
import com.xiaolin.sports.common.enums.Status;
import com.xiaolin.sports.common.enums.wechat.WechatResultCode;
import com.xiaolin.sports.model.AuditReqVO;
import com.xiaolin.sports.model.ChildSignInfo;
import com.xiaolin.sports.model.CourseInfo;
import com.xiaolin.sports.model.Grid;
import com.xiaolin.sports.model.ProductOrder;
import com.xiaolin.sports.model.SysUser;
import com.xiaolin.sports.page.Page;
import com.xiaolin.sports.pay.wepay.protocol.refundProtocol.RefundResData;
import com.xiaolin.sports.reqVo.CourseSignOrderVO;
import com.xiaolin.sports.service.ICourseService;
import com.xiaolin.sports.service.IProductOrderService;
import com.xiaolin.sports.utils.DateUtil;
import com.xiaolin.sports.utils.HttpClientUtils;
import com.xiaolin.sports.utils.JsonUtils;
import com.xiaolin.sports.utils.PropertiesUtil;
import com.xiaolin.sports.view.ChildSignView;
import com.xiaolin.sports.view.CourseBuyerView;
import com.xiaolin.sports.view.CourseSignOrderView;
import com.xiaolin.sports.vo.BuyerQueryVO;
import com.xiaolin.sports.vo.CourseQueryVO;
import com.xiaolin.sports.vo.CourseSubmitVO;

@RequestMapping("course")
@Controller
public class CourseManageController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(CourseManageController.class);

	@Autowired
	private ICourseService courseService;
	@Autowired
	private IProductOrderService productOrderService;
	
	@RequestMapping("manage")
	public String manage() {
		return "course/manage";
	}
	
	@RequestMapping("sign/record")
	public String buyRecord(){
		return "course/signRecord";
	}
	
	@RequestMapping("sign/order")
	public String signOrder() {
		return "course/signOrder";
	}
	
	@RequestMapping("json/signOrder/list")
	@ResponseBody Object signOrderList(CourseSignOrderVO vo) {
		try {
			Page<CourseSignOrderView> page = new Page<>();
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			page.setParams(vo);
			List<CourseSignOrderView> list = productOrderService.selectCourseSignOrderByPage(page);
			Grid grid = new Grid();
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("--signOrderList, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("json/order/refund")
	@ResponseBody Object orderRefundPay(Integer orderId) {
		try {
			ProductOrder order = productOrderService.selectById(orderId);
			if(order != null) {
				if(!order.getOrderStatus().equals(OrderStatus.SUCCESS.getCode())) {
					return new RspResult(Status.EXPIRED_DATA);
				}
				if(DateUtil.compare(new Date(), DateUtil.addDay(order.getPayCallbackTime(), 3)) >= 0) {
					return new RspResult(Status.ORDER_OVER_TIME);
				}
				String url = PropertiesUtil.getProperty(Configuration.getInstance().getEnv() + "_orderRefundMsg");
				AuditReqVO reqVO = new AuditReqVO();
				reqVO.setIds(String.valueOf(order.getId()));
				String result = HttpClientUtils.postJson(url, reqVO);
				RspResult rspResult = JsonUtils.jsonToObject(result, RspResult.class);
				if(rspResult.getCode().equals(Status.SUCCESS.getCode())) {
					RefundResData resData = JsonUtils.mapToObject((LinkedHashMap<String, Object>)rspResult.getData(), RefundResData.class);
					if(resData.getReturn_code().equals(WechatResultCode.SUCCESS.getCode())) {
			        	if(resData.getResult_code().equals(WechatResultCode.SUCCESS.getCode())) {
			        		return new RspResult(Status.SUCCESS);
			        	}else {
			        		return new RspResult(Status.ORDER_EXCEPTION, resData.getErr_code_des());
						}
			        }else {
		        		return new RspResult(Status.ORDER_EXCEPTION, resData.getReturn_msg());
			        }
				}
			}
		} catch (Exception e) {
			logger.error("--orderConfirmPay, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("json/sign/list")
	@ResponseBody Object courseSignList(BuyerQueryVO vo) {
		try {
			Page<ChildSignView> page = new Page<>();
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			page.setParams(vo);
			List<ChildSignView> list = courseService.selectCourseSignByPage(page);
			Grid grid = new Grid();
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("--courseSignList, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("json/buyRecord/list")
	@ResponseBody Object buyRecordList(BuyerQueryVO vo) {
		try {
			Page<CourseBuyerView> page = new Page<>();
			vo.setOrderStatus(OrderStatus.SUCCESS.getCode());
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			page.setParams(vo);
			List<CourseBuyerView> list = courseService.selectBuyRecordByPage(page);
			Grid grid = new Grid();
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("--buyRecordList, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("json/list/query")
	@ResponseBody Object jsonListQuery(CourseQueryVO vo) {
		try {
			Page<CourseInfo> page = new Page<>();
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			page.setParams(vo);
			List<CourseInfo> list = courseService.selectListByPage(page);
			Grid grid = new Grid();
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("--jsonListQuery, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	
	@RequestMapping("json/addUpdate")
	@ResponseBody Object addUpdate(CourseSubmitVO vo) {
		try {
			SysUser user = (SysUser) session.getAttribute(Constants.APP_USER);
			courseService.addAndUpdateCourse(vo, user);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("--addUpdate, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("json/edit")
	public String edit(Model model) {
		String courseId = request.getParameter("id");
		model.addAttribute("courseId", courseId);
		return "course/edit";
	}
	
	@RequestMapping("json/detail/query")
	@ResponseBody Object courseDetail(Integer courseId) {
		return courseService.selectByPrimaryKey(courseId);
	}
	
	@RequestMapping("json/edit/shelves")
	@ResponseBody Object editShelves(Integer shelves, Integer id) {
		try {
			SysUser user = (SysUser) session.getAttribute(Constants.APP_USER);
			CourseInfo vo = new CourseInfo();
			if(shelves == -1) vo.setIsDelete("Y");
			else vo.setShelves(shelves);
			vo.setId(id);
			courseService.addAndUpdateCourse(vo, user);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("--editShelves, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("json/sign/update")
	@ResponseBody Object signUpdate(ChildSignInfo vo) {
		try {
			courseService.updateChildSignInfo(vo);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("--signUpdate, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("sign/print/{id}")
	public String signPrint(Model model, @PathVariable Integer id) {
		model.addAttribute("signInfo", courseService.selectChildSignById(id));
		return "course/signPrint";
	}
	
	
}
